import { Table, Tag, Space, Popconfirm, Breadcrumb, Card, Form, Radio, Select, DatePicker, Button } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import locale from 'antd/es/date-picker/locale/zh_CN' // 日期中文化
import img404 from '@/assets/error.png'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { http } from '@/utils'
import { useStore } from '@/store'
import { observer } from 'mobx-react-lite'

const { RangePicker } = DatePicker
const { Option } = Select
const ArticlePage = () => {
  const { channelStore } = useStore()
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 120,
      render: cover => {
        return <img src={cover.images || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => <Tag color="green">审核通过</Tag>
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => goPublish(data)}
            />
            <Popconfirm
              title='确认删除该条信息吗？'
              onConfirm={() => deleteRow(data)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  const navigate = useNavigate()
  // const [channel, setChannel] = useState([])
  const [data, setData] = useState({ list: [], count: 0 })
  const [params, setParams] = useState({
    page: 1,
    per_page: 5
  })
  // useEffect(() => {
  //   // 获取频道列表
  //   async function fetchChannels() {
  //     const res = await http.get('/channels')
  //     setChannel(res.data.channels)
  //   }
  //   fetchChannels()
  // }, [])
  useEffect(() => {
    // 获取table数据
    async function tableData() {
      const res = await http.get('/mp/articles', { params })
      const { results, total_count } = res.data
      setData({ list: results, count: total_count })
    }
    tableData()
  }, [params])

  const onfinish = (value) => {
    const param = {}
    const { channel_id, date, status } = value
    if (status !== -1) {
      param.status = status
    }
    if (channel_id) {
      param.channel_id = channel_id
    }
    if (date) {
      param.begin_pubdate = date[0].format('YYYY-MM-DD')
      param.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    setParams({
      ...params,
      ...param
    })
  }
  const deleteRow = async (data) => {
    await http.delete(`/mp/articles/${data.id}`)
    setParams({
      ...params,
      page: 1
    })
  }
  const goPublish = (data) => {
    navigate(`/publish?id=${data.id}`)
  }
  const pageChange = (page) => {
    setParams({
      ...params,
      page
    })
  }
  return (
    <div>
      <Card title={<Breadcrumb
        items={[
          {
            title: '首页',
          },
          {
            title: '内容管理',
          },
        ]}
      />} bordered={false} >
        <Form
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          initialValues={{ status: -1 }}
          onFinish={onfinish}
        >
          <Form.Item label="状态" name='status'>
            <Radio.Group>
              <Radio value={-1}> 全部 </Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择文章频道"
              style={{ width: 150 }}
            >
              {
                channelStore.channelList.map((el) => (
                  <Option key={el.id} value={el.id}>{el.name}</Option>
                ))
              }
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 80 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到 ${data.count} 条结果：`}>
        <Table pagination={
          {
            position: ['bottomCenter'],
            current: params.page,
            pageSize: params.per_page,
            total: data.count,
            onChange: pageChange
          }
        } rowKey="id" columns={columns} dataSource={data.list} />
      </Card>
    </div>
  )
}
export default observer(ArticlePage)